﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Animation;
using System.Windows.Shapes;
using VAdvantage.Model;
using VAdvantage.Logging;
using VAdvantage.Controls;
using VAdvantage.Utility;
using System.ComponentModel;
using VAdvantage.DataBase;
using System.Text;
using System.Data;
using VAdvantage.Classes;

namespace VAdvantage.Dialogs
{
    public partial class VPAttributesDialog : ChildWindow
    {
        public VPAttributesDialog()
        {
            InitializeComponent();
            LayoutRoot.Background = new SolidColorBrush(GlobalVariable.WINDOW_BACK_COLOR);
        }

        #region "Declaration"
        private int _windowNo;
        private MAttributeSetInstance _masi;
        private int _M_AttributeSetInstance_ID;
        private int _M_Locator_ID;
        private String _M_AttributeSetInstanceName;
        private int _M_Product_ID;
        private int _C_BPartner_ID;
        private int _AD_Column_ID;
        private int _windowNoParent;
        /**	Enter Product Attributes		*/
        private bool _productWindow = false;
        /**	Change							*/
        private bool _changed = false;

        private VLogger log = VLogger.GetVLogger(typeof(VPAttributesDialog).FullName);
        /** Row Counter					*/
        private int _row = 0;
        /** List of Editors				*/
        private List<IControl> _editors = new List<IControl>();
        /** Length of Instance value (40)	*/
        private const int INSTANCE_VALUE_LENGTH = 40;

        private MenuItem mZoom;

        private Controls.VCheckBox chkNewEdit = new Controls.VCheckBox();
        private Controls.VButton btnSelect = new Controls.VButton(Envs.LoadImageSource("PAttribute10.png"));
        //	Lot
        private Controls.VTextBox txtLotString = new Controls.VTextBox("Lot", false, false, true, 20, 20, null, null, Controls.VTextBox.TextType.Text, Classes.DisplayType.String);

        private Controls.VComboBox cmbLot = null;
        private Controls.VButton btnLot = new Controls.VButton(Msg.GetMsg(Envs.GetContext(), "New"));
        private Controls.VTextBox txtSerNo = new Controls.VTextBox("SerNo", false, false, true, 20, 20, null, null, Controls.VTextBox.TextType.Text, Classes.DisplayType.String);

        private Controls.VButton btnSerNo = new Controls.VButton(Msg.GetMsg(Envs.GetContext(), "New"));
        //	Date
        private Controls.VDateTimePicker dtpicGuaranteeDate = new Controls.VDateTimePicker("GuaranteeDate", false, false, true, Classes.DisplayType.Date, Msg.Translate(Envs.GetContext(), "GuaranteeDate"));
        //
        private Controls.VTextBox txtDescription = new Controls.VTextBox();

        Dictionary<MAttribute, KeyValuePair<MAttributeInstance, MAttributeValue[]>> attributesList = new Dictionary<MAttribute, KeyValuePair<MAttributeInstance, MAttributeValue[]>>(4);

        #endregion


        public VPAttributesDialog(int M_AttributeSetInstance_ID,
        int M_Product_ID, int M_Locator_ID, int C_BPartner_ID,
        bool productWindow, int AD_Column_ID, int windowNo)
            : this()
        {
            this.Title = Msg.Translate(Envs.GetContext(), "M_AttributeSetInstance_ID");
            log.Config("M_AttributeSetInstance_ID=" + M_AttributeSetInstance_ID
                + ", M_Product_ID=" + M_Product_ID
                + ", C_BPartner_ID=" + C_BPartner_ID
                + ", ProductW=" + productWindow + ", Column=" + AD_Column_ID);
            _windowNo = Envs.CreateWindowNo(this);
            _M_AttributeSetInstance_ID = M_AttributeSetInstance_ID;
            _M_Product_ID = M_Product_ID;
            _C_BPartner_ID = C_BPartner_ID;
            _productWindow = productWindow;
            _AD_Column_ID = AD_Column_ID;
            _windowNoParent = windowNo;
            //************ Change ************
            _M_Locator_ID = M_Locator_ID;

            if (!InitAttributes())
            {
                // this.Dispose();
                //return;
            }

            SetBusy(true);


        }

        private void SetBusy(bool isBusy)
        {
            busyWindow.Visibility = isBusy ? System.Windows.Visibility.Visible : System.Windows.Visibility.Collapsed;
            txtBusy.Visibility = isBusy ? System.Windows.Visibility.Visible : System.Windows.Visibility.Collapsed;
        }

        private bool InitAttributes()
        {
            if (_M_Product_ID == 0)
                return false;

            MAttributeSet aset = null;
            MAttribute[] attributes = null;

            BackgroundWorker bgw = new BackgroundWorker();
            bgw.DoWork += (sd, ed) =>
            {
                ed.Result = false;
                //	Get Model
                _masi = MAttributeSetInstance.Get(Envs.GetContext(), _M_AttributeSetInstance_ID, _M_Product_ID);
                if (_masi == null)
                {
                    log.Severe("No Model for M_AttributeSetInstance_ID=" + _M_AttributeSetInstance_ID + ", M_Product_ID=" + _M_Product_ID);
                    return;
                }
                Envs.GetContext().SetContext(_windowNo, "M_AttributeSet_ID", _masi.GetM_AttributeSet_ID());

                //	Get Attribute Set
                aset = _masi.GetMAttributeSet();
                //	Product has no Attribute Set
                if (aset == null)
                {
                    Dispatcher.BeginInvoke(() => Classes.ShowMessage.Error("PAttributeNoAttributeSet", null));
                    return;
                }

                //	Product has no Instance Attributes
                if (!_productWindow && !aset.IsInstanceAttribute())
                {
                    Dispatcher.BeginInvoke(() => Classes.ShowMessage.Error("PAttributeNoInstanceAttribute", null));
                    //ADialog.error(m_WindowNo, this, "PAttributeNoInstanceAttribute");
                    return;
                }


                if (_productWindow)
                {
                    attributes = aset.GetMAttributes(false);
                    log.Fine("Product Attributes=" + attributes.Length);

                }
                else
                {
                    attributes = aset.GetMAttributes(true);
                }


                for (int i = 0; i < attributes.Length; i++)
                {
                    MAttribute a = attributes[i];
                    MAttributeInstance ins = a.GetMAttributeInstance(_M_AttributeSetInstance_ID);
                    MAttributeValue[] v = null;

                    if (MAttribute.ATTRIBUTEVALUETYPE_List.Equals(a.GetAttributeValueType()))
                    {
                        v = a.GetMAttributeValues();
                    }
                    attributesList[a] = new KeyValuePair<MAttributeInstance, MAttributeValue[]>(ins, v);
                }


                ed.Result = true;
            };

            bgw.RunWorkerCompleted += (sc, ec) =>
            {

                if (ec.Result == null || !(bool)ec.Result)
                {
                    this.DialogResult = false;
                    return;
                }

                if (_productWindow)
                {
                    tblFields.RowDefinitions.Add(new RowDefinition() { Height = GridLength.Auto });
                    for (int i = 0; i < attributes.Length; i++)
                        AddAttributeLine(attributes[i], true, !_productWindow);
                }
                else
                {
                    ////	New/Edit - Selection
                    // //chkNewEdit.AutoSize = true;
                    /// //chkNewEdit.Anchor = System.Windows.Forms.AnchorStyles.Right;
                    chkNewEdit.HorizontalAlignment = System.Windows.HorizontalAlignment.Right;


                    if (_M_AttributeSetInstance_ID == 0)		//	new
                        chkNewEdit.Content = Msg.GetMsg(Envs.GetContext(), "NewRecord");
                    else
                        chkNewEdit.Content = Msg.GetMsg(Envs.GetContext(), "EditRecord");


                    chkNewEdit.Checked += new RoutedEventHandler(chkNewEdit_CheckedChanged);
                    chkNewEdit.Unchecked += new RoutedEventHandler(chkNewEdit_CheckedChanged);


                    //tblFields.Controls.Add(chkNewEdit, 0, tblFields.RowCount - 1);
                    tblFields.RowDefinitions.Add(new RowDefinition() { Height = GridLength.Auto });
                    tblFields.Children.Add(chkNewEdit);
                    Grid.SetColumn(chkNewEdit, 0);
                    Grid.SetRow(chkNewEdit, tblFields.RowDefinitions.Count - 1);


                    btnSelect.Text = Msg.GetMsg(Envs.GetContext(), "SelectExisting");
                    //btnSelect.AutoSize = true;
                    btnSelect.Click += new RoutedEventHandler(btnSelect_Click);
                    tblFields.Children.Add(btnSelect);
                    btnSelect.HorizontalAlignment = System.Windows.HorizontalAlignment.Left;
                    btnSelect.Margin = new Thickness(2);

                    Grid.SetColumn(btnSelect, 1);
                    Grid.SetRow(btnSelect, tblFields.RowDefinitions.Count - 1);


                    tblFields.RowDefinitions.Add(new RowDefinition() { Height = GridLength.Auto });
                    //	All Attributes

                    log.Fine("Instance Attributes=" + attributes.Length);
                    for (int i = 0; i < attributes.Length; i++)
                    {
                        AddAttributeLine(attributes[i], false, false);
                    }
                }


                ////	Lot
                if (!_productWindow && aset.IsLot())
                {
                    VLabel label = GetLabel(Msg.Translate(Envs.GetContext(), "Lot"));
                    //tblFields.Controls.Add(label, 0, tblFields.RowCount - 1);
                    tblFields.Children.Add(label);
                    Grid.SetRow(label, tblFields.RowDefinitions.Count - 1);
                    Grid.SetColumn(label, 0);

                    //    tblFields.Controls.Add(txtLotString, 1, tblFields.RowCount - 1);
                    //    txtLotString.Dock = System.Windows.Forms.DockStyle.Fill;
                    tblFields.Children.Add(txtLotString);
                    Grid.SetRow(txtLotString, tblFields.RowDefinitions.Count - 1);
                    Grid.SetColumn(txtLotString, 1);

                    txtLotString.Margin = new Thickness(2);

                    tblFields.RowDefinitions.Add(new RowDefinition() { Height = GridLength.Auto });
                    //    tblFields.RowCount++;

                    txtLotString.Text = _masi.GetLot();


                    label = GetLabel(Msg.Translate(Envs.GetContext(), "M_Lot_ID"));
                    //    tblFields.Controls.Add(label, 0, tblFields.RowCount - 1);
                    tblFields.Children.Add(label);
                    Grid.SetColumn(label, 0);
                    Grid.SetRow(label, tblFields.RowDefinitions.Count - 1);


                    int row = tblFields.RowDefinitions.Count - 1;


                    System.Threading.ThreadPool.QueueUserWorkItem(delegate
                    {

                        String sql = "SELECT M_Lot_ID, Name "
                            + "FROM M_Lot l "
                            + "WHERE EXISTS (SELECT M_Product_ID FROM M_Product p "
                                + "WHERE p.M_AttributeSet_ID=" + _masi.GetM_AttributeSet_ID()
                                + " AND p.M_Product_ID=l.M_Product_ID)";

                        KeyNamePair[] data = DB.GetKeyNamePairs(sql, true);

                        Dispatcher.BeginInvoke(delegate
                        {
                            cmbLot = new VAdvantage.Controls.VComboBox(data);

                            tblFields.Children.Add(cmbLot);
                            Grid.SetColumn(cmbLot, 1);
                            Grid.SetRow(cmbLot, row);
                            cmbLot.Margin = new Thickness(2);


                            if (_masi.GetM_Lot_ID() != 0)
                            {
                                for (int i = 1; i < cmbLot.Items.Count; i++)
                                {
                                    KeyNamePair pp = (KeyNamePair)cmbLot.Items[i];
                                    if (pp.GetKey() == _masi.GetM_Lot_ID())
                                    {
                                        cmbLot.SelectedIndex = i;
                                        txtLotString.IsReadOnly = true;
                                        break;
                                    }
                                }
                            }
                            //    cmbLot.SelectedIndexChanged += new EventHandler(cmbLot_SelectedIndexChanged);
                            cmbLot.SelectionChanged += new SelectionChangedEventHandler(cmbLot_SelectionChanged);
                            mZoom = new MenuItem();
                            mZoom.Header = Msg.GetMsg(Envs.GetContext(), "Zoom");
                            mZoom.Icon = Envs.LoadImageSource("Zoom10.png");
                            mZoom.Click += new RoutedEventHandler(mZoom_Click);
                            ContextMenu ctx = new ContextMenu();
                            ctx.Items.Add(mZoom);
                            ContextMenuService.SetContextMenu(cmbLot, ctx);

                        });
                    });
                    tblFields.RowDefinitions.Add(new RowDefinition() { Height = GridLength.Auto });

                    //    cmbLot.Dock = System.Windows.Forms.DockStyle.Fill;


                    //    tblFields.Controls.Add(cmbLot, 1, tblFields.RowCount - 1);


                    //    tblFields.RowCount++;


                    //	New Lot Button
                    if (_masi.GetMAttributeSet().GetM_LotCtl_ID() != 0)
                    {
                        if (MRole.GetDefault().IsTableAccess(MLot.Table_ID, false)
                            && MRole.GetDefault().IsTableAccess(MLotCtl.Table_ID, false))
                        {
                            int row1 = tblFields.RowDefinitions.Count - 1;

                            System.Threading.ThreadPool.QueueUserWorkItem(delegate
                            {
                                if (!_masi.IsExcludeLot(_AD_Column_ID, Envs.GetContext().IsSOTrx(_windowNoParent)))
                                {
                                    Dispatcher.BeginInvoke(delegate
                                    {
                                        tblFields.Children.Add(btnLot);
                                        Grid.SetRow(btnLot, row1);
                                        Grid.SetColumn(btnLot, 1);
                                        btnLot.HorizontalAlignment = System.Windows.HorizontalAlignment.Right;
                                        btnLot.Margin = new Thickness(2);
                                        btnLot.Click += new RoutedEventHandler(btnLot_Click);
                                    });
                                }
                            });

                            tblFields.RowDefinitions.Add(new RowDefinition() { Height = GridLength.Auto });
                            //tblFields.RowCount++;
                        }
                    }
                    //    cmbLot.ContextMenuStrip = this.ctxStrip;

                }



                //	SerNo
                if (!_productWindow && aset.IsSerNo())
                {
                    VLabel label = GetLabel(Msg.Translate(Envs.GetContext(), "SerNo"));

                    txtSerNo.Text = _masi.GetSerNo();
                    tblFields.Children.Add(label);
                    Grid.SetColumn(label, 0);
                    Grid.SetRow(label, tblFields.RowDefinitions.Count - 1);

                    //tblFields.Controls.Add(label, 0, tblFields.RowCount - 1);

                    tblFields.Children.Add(txtSerNo);
                    txtSerNo.Margin = new Thickness(2);
                    Grid.SetColumn(txtSerNo, 1);
                    Grid.SetRow(txtSerNo, tblFields.RowDefinitions.Count - 1);
                    // tblFields.Controls.Add(txtSerNo, 1, tblFields.RowCount - 1);
                    //txtSerNo.Dock = System.Windows.Forms.DockStyle.Fill;
                    tblFields.RowDefinitions.Add(new RowDefinition() { Height = GridLength.Auto });

                    //	New SerNo Button
                    if (_masi.GetMAttributeSet().GetM_SerNoCtl_ID() != 0)
                    {
                        if (MRole.GetDefault().IsTableAccess(MSerNoCtl.Table_ID, false))
                        //&& !_masi.IsExcludeSerNo(_AD_Column_ID, Envs.GetContext().IsSOTrx(_windowNoParent)))
                        {
                            //tblFields.Controls.Add(btnSerNo, 1, tblFields.RowCount - 1);

                            int row2 = tblFields.RowDefinitions.Count - 1;

                            System.Threading.ThreadPool.QueueUserWorkItem(delegate
                            {
                                if (!_masi.IsExcludeLot(_AD_Column_ID, Envs.GetContext().IsSOTrx(_windowNoParent)))
                                {
                                    Dispatcher.BeginInvoke(delegate
                                    {
                                        tblFields.Children.Add(btnSerNo);
                                        Grid.SetColumn(btnSerNo, 1);
                                        Grid.SetRow(btnSerNo, row2);
                                        btnSerNo.Margin = new Thickness(2);
                                        //btnSerNo.AutoSize = true;
                                        btnSerNo.HorizontalAlignment = System.Windows.HorizontalAlignment.Right;
                                        btnSerNo.Click += new RoutedEventHandler(btnSerNo_Click);
                                    });
                                }
                            });

                            //btnSerNo.Anchor = System.Windows.Forms.AnchorStyles.Right;
                            tblFields.RowDefinitions.Add(new RowDefinition() { Height = GridLength.Auto });
                            //tblFields.RowCount++;
                        }
                    }
                }	//	SerNo

                ////	GuaranteeDate
                if (!_productWindow && aset.IsGuaranteeDate())
                {
                    VLabel label = GetLabel(Msg.Translate(Envs.GetContext(), "GuaranteeDate"));

                    if (_M_AttributeSetInstance_ID == 0)
                        dtpicGuaranteeDate.SetValue(_masi.GetGuaranteeDate(true));
                    else
                        dtpicGuaranteeDate.SetValue(_masi.GetGuaranteeDate());

                    tblFields.Children.Add(label);
                    //tblFields.Controls.Add(label, 0, tblFields.RowCount - 1);
                    Grid.SetRow(label, tblFields.RowDefinitions.Count - 1);
                    Grid.SetColumn(label, 0);

                    tblFields.Children.Add(dtpicGuaranteeDate);
                    Grid.SetRow(dtpicGuaranteeDate, tblFields.RowDefinitions.Count - 1);
                    Grid.SetColumn(dtpicGuaranteeDate, 1);
                    dtpicGuaranteeDate.Margin = new Thickness(2);

                    //tblFields.Controls.Add(dtpicGuaranteeDate, 1, tblFields.RowCount - 1);
                    //dtpicGuaranteeDate.Dock = System.Windows.Forms.DockStyle.Fill;
                    //tblFields.RowCount++;
                    tblFields.RowDefinitions.Add(new RowDefinition() { Height = GridLength.Auto });
                }


                if (tblFields.RowDefinitions.Count - 1 <= 3 && tblFields.Children.Count <= 0)
                {
                    Classes.ShowMessage.Error("PAttributeNoInfo", null);
                    this.DialogResult = false;
                    return;
                }

                //	New/Edit Window
                if (!_productWindow)
                {
                    chkNewEdit.IsChecked = _M_AttributeSetInstance_ID == 0;
                    //cmd_newEdit();
                }

                //	Attrribute Set Instance Description
                VLabel label1 = GetLabel(Msg.Translate(Envs.GetContext(), "Description"));

                txtDescription.Text = _masi.GetDescription();
                txtDescription.IsReadOnly = true;

                //            tblFields.Controls.Add(label1, 0, tblFields.RowCount - 1);
                tblFields.Children.Add(label1);
                Grid.SetColumn(label1, 0);
                Grid.SetRow(label1, tblFields.RowDefinitions.Count - 1);

                tblFields.Children.Add(txtDescription);
                Grid.SetColumn(txtDescription, 1);
                Grid.SetRow(txtDescription, tblFields.RowDefinitions.Count - 1);

                txtDescription.Margin = new Thickness(2);
                //tblFields.Controls.Add(txtDescription, 1, tblFields.RowCount - 1);
                // txtDescription.Dock = System.Windows.Forms.DockStyle.Fill;
                tblFields.RowDefinitions.Add(new RowDefinition() { Height = GridLength.Auto });
                //tblFields.RowCount++;
                //	Window usually to wide (??)

                SetBusy(false);
            };
            bgw.RunWorkerAsync();

            return true;

        }

        void mZoom_Click(object sender, RoutedEventArgs e)
        {

            int M_Lot_ID = 0;
            KeyNamePair pp = (KeyNamePair)cmbLot.SelectedItem;
            if (pp != null)
                M_Lot_ID = pp.GetKey();
            Classes.Query zoomQuery = new Classes.Query("M_Lot");
            zoomQuery.AddRestriction("M_Lot_ID", Classes.Query.EQUAL, M_Lot_ID);
            log.Info(zoomQuery.ToString());
            //
            //this.Cursor  = 
            //setCursor(Cursor.getPredefinedCursor(Cursor.WAIT_CURSOR));
            //
            //this.UseWaitCursor = true;
            this.Cursor = Cursors.Wait;

            int AD_Window_ID = 257;		//	Lot
            Apps.AWindow frame = new Apps.AWindow();
            if (frame.InitWindow(AD_Window_ID, zoomQuery))
            {
                //frame.StartPosition = System.Windows.Forms.FormStartPosition.CenterScreen;
                // frame.Show();
                // AEnv.showScreen(frame, SwingConstants.EAST);
            }
            //  async window - not able to get feedback
            frame = null;
            //
            this.Cursor = Cursors.Arrow;
        }

        void btnSelect_Click(object sender, RoutedEventArgs e)
        {
            SetBusy(true);
            System.Threading.ThreadPool.QueueUserWorkItem(delegate
            {
                Cmd_Select();
                //if (Cmd_Select())
                //{
                //    Dispatcher.BeginInvoke(delegate
                //    {
                //        //this.Close();
                //        this.DialogResult = true;
                //    });
                //}
            });
        }

        private bool Cmd_Select()
        {
            log.Config("");
            int M_Warehouse_ID = Envs.GetContext().GetContextAsInt(_windowNoParent, "M_Warehouse_ID");
            String title = "";
            //	Get Text
            String sql = "SELECT p.Name, w.Name FROM M_Product p, M_Warehouse w "
                + "WHERE p.M_Product_ID=@1 AND w.M_Warehouse_ID=@2";
            System.Data.IDataReader dr = null;
            System.Data.SqlClient.SqlParameter[] param = null;
            try
            {
                param = new System.Data.SqlClient.SqlParameter[2];
                param[0] = new System.Data.SqlClient.SqlParameter("@1", _M_Product_ID);
                param[1] = new System.Data.SqlClient.SqlParameter("@2", M_Warehouse_ID);

                dr = DataBase.DB.ExecuteReader(sql, param);

                if (dr.Read())
                    title = dr[0].ToString() + " - " + dr[1].ToString();
                dr.Close();
                dr = null;
                param = null;




            }
            catch (Exception e)
            {
                if (dr != null)
                {
                    dr.Close();
                }
                log.Log(Level.SEVERE, sql, e);
            }
            //try
            //{
            //    if (dr != null)
            //        dr.Close();
            //    dr = null;
            //    param = null;
            //}
            //catch (Exception e)
            //{
            //    dr = null;
            //    log.Log(Level.SEVERE, sql, e);
            //}
            int AttributeSetInstance_ID = -1;
            bool chk = false;
            bool flag = false;
            Dispatcher.BeginInvoke(delegate
            {
                Search.PAttributeInstance pai = new VAdvantage.Search.PAttributeInstance(new SilverlightDesktop.Controls.Form(), title,
                    M_Warehouse_ID, _M_Locator_ID, _M_Product_ID, _C_BPartner_ID);

                pai.Closing += (s, ev) =>
                {
                    AttributeSetInstance_ID = pai.GetM_AttributeSetInstance_ID();
                    if (AttributeSetInstance_ID != -1)
                    {
                        _M_AttributeSetInstance_ID = pai.GetM_AttributeSetInstance_ID();
                        _M_AttributeSetInstanceName = pai.GetM_AttributeSetInstanceName();
                        _M_Locator_ID = pai.GetM_Locator_ID();
                        _changed = true;
                        flag = true;
                        this.DialogResult = true;
                    }
                    chk = true;
                    // flag = false;
                };
                SetBusy(false);
                pai.Show();
            });

            //while (!chk)
            //{ }
            return flag;
            //if (AttributeSetInstance_ID != -1)
            //{
            //    return true;
            //}
            //return false;
        }

        void chkNewEdit_CheckedChanged(object sender, RoutedEventArgs e)
        {
            Cmd_NewEdit();
        }


        /// <summary>
        ///Instance New/Edit
        /// </summary>
        private void Cmd_NewEdit()
        {
            bool rw = chkNewEdit.IsChecked == null || !(bool)chkNewEdit.IsChecked ? false : true;
            log.Config("R/W=" + rw + " " + _masi);
            //
            txtLotString.SetReadOnly(!(rw && _masi.GetM_Lot_ID() == 0));
            if (cmbLot != null)
            {
                //   fieldLot.setReadWrite(rw);
                cmbLot.IsEnabled = rw;
            }
            //bLot.setReadWrite(rw);
            btnLot.IsEnabled = rw;
            txtSerNo.IsReadOnly = !rw;
            btnSerNo.IsEnabled = rw;
            dtpicGuaranteeDate.IsEnabled = rw;
            //fieldGuaranteeDate.setReadWrite(rw);
            //
            for (int i = 0; i < _editors.Count; i++)
            {
                IControl editor = (IControl)_editors[i];
                editor.SetReadOnly(!rw);
            }
        }

        void btnSerNo_Click(object sender, RoutedEventArgs e)
        {
            SetBusy(true);
            System.Threading.ThreadPool.QueueUserWorkItem(delegate
            {
                String text = _masi.GetSerNo(true);

                Dispatcher.BeginInvoke(delegate
                {
                    txtSerNo.Text = text;
                    SetBusy(false);
                });
            });
        }

        private void btnLot_Click(object sender, RoutedEventArgs e)
        {
            SetBusy(true);

            System.Threading.ThreadPool.QueueUserWorkItem(delegate
            {
                KeyNamePair pp = _masi.CreateLot(_M_Product_ID);

                Dispatcher.BeginInvoke(delegate
                {
                    if (pp != null)
                    {
                        cmbLot.Items.Add(pp);
                        cmbLot.SelectedItem = pp;
                    }
                    SetBusy(false);

                });
                //fieldLot.setSelectedItem(pp);
            });
        }

        void cmbLot_SelectionChanged(object sender, SelectionChangedEventArgs e)
        {
            KeyNamePair pp = (KeyNamePair)cmbLot.SelectedItem;
            if (pp != null && pp.GetKey() != -1)
            {
                txtLotString.Text = pp.GetName();
                txtLotString.IsReadOnly = true;// fieldLotString.setEditable(false);
                _masi.SetM_Lot_ID(pp.GetKey());
            }
            else
            {
                txtLotString.IsReadOnly = false;// fieldLotString.setEditable(true);
                _masi.SetM_Lot_ID(0);
            }
        }

        private VLabel GetLabel(string text)
        {
            VLabel lbl = new VLabel();
            lbl.Content = text;
            // lbl.Anchor = System.Windows.Forms.AnchorStyles.Right;
            lbl.HorizontalAlignment = System.Windows.HorizontalAlignment.Right;
            //lbl.Margin = new Thickness(2,7,4,7);
            //lbl.AutoSize = true;
            return lbl;
        }

        private void AddAttributeLine(MAttribute attribute, bool product, bool readOnly)
        {
            log.Fine(attribute + ", Product=" + product + ", R/O=" + readOnly);
            VLabel label = GetLabel(attribute.GetName());
            if (product)
                label.FontWeight = FontWeights.Bold;// new System.Drawing.Font(label.Font, System.Drawing.FontStyle.Bold);
            if (attribute.GetDescription() != null)
            {
                //System.Windows.Forms.ToolTip tp = new System.Windows.Forms.ToolTip();
                //tp.SetToolTip(label, attribute.GetDescription());
            }
            tblFields.Children.Add(label);
            Grid.SetColumn(label, 0);
            //if (tblFields.RowDefinitions.Count != 0)
            //{
            // Grid.SetRow(label, 0);
            Grid.SetRow(label, tblFields.RowDefinitions.Count - 1);
            //Grid.SetRow(label, tblFields.RowDefinitions.Count);
            //}

            //, 0, tblFields.RowCount - 1);
            //centerPanel.add(label, new ALayoutConstraint(m_row++, 0));
            //
            MAttributeInstance instance = attributesList[attribute].Key;// attribute.GetMAttributeInstance(_M_AttributeSetInstance_ID);

            if (MAttribute.ATTRIBUTEVALUETYPE_List.Equals(attribute.GetAttributeValueType()))
            {

                int rowCount = tblFields.RowDefinitions.Count - 1;
                int editorCount = _editors.Count;

                MAttributeValue[] values = attributesList[attribute].Value;

                VComboBox cmb = new VComboBox(values);
                //cmb.Dock = System.Windows.Forms.DockStyle.Fill;
                //CComboBox editor = new CComboBox(values);
                bool found = false;
                if (instance != null)
                {
                    for (int i = 0; i < values.Length; i++)
                    {
                        if (values[i] != null && values[i].GetM_AttributeValue_ID() == instance.GetM_AttributeValue_ID())
                        {
                            cmb.SelectedIndex = i;
                            found = true;
                            break;
                        }
                    }
                    if (found)
                        log.Fine("Attribute=" + attribute.GetName() + " #" + values.Length + " - found: " + instance);
                    else
                        log.Warning("Attribute=" + attribute.GetName() + " #" + values.Length + " - NOT found: " + instance);
                }
                else
                    log.Fine("Attribute=" + attribute.GetName() + " #" + values.Length + " no instance");
                //label.setLabelFor(editor);
                //tblFields.Controls.Add(cmb, 1, tblFields.RowCount - 1);

                cmb.Margin = new Thickness(2);

                tblFields.Children.Add(cmb);
                Grid.SetColumn(cmb, 1);
                //if (tblFields.RowDefinitions.Count != 0)
                //{
                //Grid.SetRow(cmb, 0);
                Grid.SetRow(cmb, tblFields.RowDefinitions.Count - 1);
                // Grid.SetRow(cmb, tblFields.RowDefinitions.Count);
                //}


                //centerPanel.add(editor, null);
                if (readOnly)
                    cmb.IsEnabled = false;
                else
                    _editors.Add(cmb);
            }
            else if (MAttribute.ATTRIBUTEVALUETYPE_Number.Equals(attribute.GetAttributeValueType()))
            {
                VAmountTextBox editor = new VAmountTextBox(attribute.GetName(), attribute.IsMandatory(),
                    false, true, Classes.DisplayType.Number, attribute.GetName());
                // editor.Dock = System.Windows.Forms.DockStyle.Fill;
                if (instance != null)
                    editor.SetValue(instance.GetValueNumber());
                else
                    editor.SetValue(Envs.ZERO);
                //label.setLabelFor(editor);
                //tblFields.Controls.Add(editor, 1, tblFields.RowCount - 1);

                tblFields.Children.Add(editor);
                Grid.SetColumn(editor, 1);
                Grid.SetRow(editor, tblFields.RowDefinitions.Count - 1);
                editor.Margin = new Thickness(2);

                if (readOnly)
                    editor.IsEnabled = false;
                else
                    _editors.Add(editor);
            }
            else	//	Text Field
            {
                VTextBox editor = new VTextBox(attribute.GetName(), attribute.IsMandatory(),
                    false, true, 20, INSTANCE_VALUE_LENGTH, null, null, VTextBox.TextType.Text, Classes.DisplayType.String);
                //editor.Dock = System.Windows.Forms.DockStyle.Fill;
                if (instance != null)
                    editor.SetValue(instance.GetValue());

                //tblFields.Controls.Add(editor, 1, tblFields.RowCount - 1);
                tblFields.Children.Add(editor);
                Grid.SetColumn(editor, 1);
                Grid.SetRow(editor, tblFields.RowDefinitions.Count - 1);
                editor.Margin = new Thickness(2);
                if (readOnly)
                    editor.IsEnabled = false;// .setEnabled(false);
                else
                    _editors.Add(editor);
            }

            tblFields.RowDefinitions.Add(new RowDefinition() { Height = GridLength.Auto });
            //tblFields.RowCount++;
        }


        private void OKButton_Click(object sender, RoutedEventArgs e)
        {
            bool flag = true;
            if ((bool)chkNewEdit.IsChecked)
            {
                string text = txtLotString.Text;
                flag = false;
                System.Threading.ThreadPool.QueueUserWorkItem(delegate
                {
                    String sql = "select count(*) from ad_column where columnname = 'UniqueLot' and ad_table_id = (select ad_table_id from ad_table where tablename = 'M_AttributeSet')";
                    int count = Util.GetValueOfInt(VAdvantage.DataBase.DB.ExecuteScalar(sql));
                    if (count > 0)
                    {
                        bool check = CheckAttrib(text);
                        if (check)
                        {
                            flag = true;
                            Dispatcher.BeginInvoke(delegate
                            {
                                ShowMessage.Info("LotNoExists", true, null, null);
                                this.DialogResult = true;
                                return;
                            });
                        }
                    }
                    if (!flag)
                    {
                        Dispatcher.BeginInvoke(delegate
                        {
                            SetBusy(true);
                            SaveSelection();
                            //  this.DialogResult = true;
                        });
                    }

                });
            }

            if (flag)
            {
                SetBusy(true);
                SaveSelection();
            }

            // End Change
            //this.DialogResult = System.Windows.Forms.DialogResult.OK;

            // this.Close();
        }


        /// <summary>
        ///Save Selection
        /// </summary>
        /// <returns>true if saved</returns>
        private void SaveSelection()
        {
            String strLotString = "", strSerNo = "";
            DateTime? dtGuaranteeDate = null;

            if (!_productWindow && txtLotString != null)
            {
                strLotString = txtLotString.Text;
            }	//	L

            if (!_productWindow && txtSerNo != null)
            {
                log.Fine("SerNo=" + txtSerNo.Text);
                strSerNo = txtSerNo.Text;
            }

            if (!_productWindow && dtpicGuaranteeDate != null)
            {
                dtGuaranteeDate = (DateTime?)dtpicGuaranteeDate.GetValue();
            }	//	Gua


            BackgroundWorker bgw = new BackgroundWorker();

            MAttributeSet aset = null;
            MAttribute[] attributes = null;

            String mandatory = "";

            bgw.DoWork += (sd, ed) =>
            {
                ed.Result = true;
                aset = _masi.GetMAttributeSet();
                if (aset == null)
                {
                    ed.Result = false;
                    return;
                }



                _changed = false;

                if (!_productWindow && aset.IsLot())
                {
                    log.Fine("Lot=" + strLotString);
                    String text = strLotString;
                    _masi.SetLot(text);
                    if (aset.IsLotMandatory() && (text == null || text.Length == 0))
                        mandatory += " - " + Msg.Translate(Envs.GetContext(), "Lot");
                    _changed = true;
                }	//	Lot
                if (!_productWindow && aset.IsSerNo())
                {
                    log.Fine("SerNo=" + strSerNo);
                    String text = strSerNo;
                    _masi.SetSerNo(text);
                    if (aset.IsSerNoMandatory() && (text == null || text.Length == 0))
                        mandatory += " - " + Msg.Translate(Envs.GetContext(), "SerNo");
                    _changed = true;
                }
                if (!_productWindow && aset.IsGuaranteeDate())
                {
                    log.Fine("GuaranteeDate=" + dtGuaranteeDate);
                    DateTime? ts = dtGuaranteeDate;
                    _masi.SetGuaranteeDate(ts);
                    if (aset.IsGuaranteeDateMandatory() && ts == null)
                        mandatory += " - " + Msg.Translate(Envs.GetContext(), "GuaranteeDate");
                    _changed = true;
                }	//	GuaranteeDate

                //	***	Save Attributes ***
                //	New Instance
                if (_changed || _masi.GetM_AttributeSetInstance_ID() == 0)
                {
                    _masi.Save();
                    _M_AttributeSetInstance_ID = _masi.GetM_AttributeSetInstance_ID();
                    _M_AttributeSetInstanceName = _masi.GetDescription();
                }

                //	Save Instance Attributes
                attributes = aset.GetMAttributes(!_productWindow);

            };

            bgw.RunWorkerCompleted += (sc, ec) =>
            {

                if (!(bool)ec.Result)
                {
                    this.DialogResult = false;
                    return;

                }


                Dictionary<MAttribute, object> lst = new Dictionary<MAttribute, object>();

                for (int i = 0; i < attributes.Length; i++)
                {
                    if (MAttribute.ATTRIBUTEVALUETYPE_List.Equals(attributes[i].GetAttributeValueType()))
                    {
                        VComboBox editor = (VComboBox)_editors[i];

                        MAttributeValue value = (MAttributeValue)(editor.SelectedItem == DBNull.Value ? null : editor.SelectedItem);
                        log.Fine(attributes[i].GetName() + "=" + value);
                        if (attributes[i].IsMandatory() && value == null)
                            mandatory += " - " + attributes[i].GetName();
                        // attributes[i].SetMAttributeInstance(_M_AttributeSetInstance_ID, value);
                        lst[attributes[i]] = value;

                    }
                    else if (MAttribute.ATTRIBUTEVALUETYPE_Number.Equals(attributes[i].GetAttributeValueType()))
                    {
                        Controls.VAmountTextBox editor = (Controls.VAmountTextBox)_editors[i];
                        decimal? value = (Decimal?)editor.GetValue();
                        log.Fine(attributes[i].GetName() + "=" + value);
                        if (attributes[i].IsMandatory() && value == null)
                            mandatory += " - " + attributes[i].GetName();

                        //attributes[i].SetMAttributeInstance(_M_AttributeSetInstance_ID, value);
                        lst[attributes[i]] = value;
                    }
                    else
                    {
                        Controls.VTextBox editor = (Controls.VTextBox)_editors[i];
                        String value = editor.GetText();
                        log.Fine(attributes[i].GetName() + "=" + value);
                        if (attributes[i].IsMandatory() && (value == null || value.Length == 0))
                            mandatory += " - " + attributes[i].GetName();

                        //attributes[i].SetMAttributeInstance(_M_AttributeSetInstance_ID, value);
                        lst[attributes[i]] = value;
                    }
                    _changed = true;
                }

                //	Save Model
                if (_changed)
                {
                    System.Threading.ThreadPool.QueueUserWorkItem(delegate
                    {

                        for (int i = 0; i < attributes.Length; i++)
                        {
                            if (MAttribute.ATTRIBUTEVALUETYPE_List.Equals(attributes[i].GetAttributeValueType()))
                            {
                                VComboBox editor = (VComboBox)_editors[i];

                                MAttributeValue value = lst[attributes[i]] != null ? lst[attributes[i]] as MAttributeValue : null;
                                attributes[i].SetMAttributeInstance(_M_AttributeSetInstance_ID, value);

                            }
                            else if (MAttribute.ATTRIBUTEVALUETYPE_Number.Equals(attributes[i].GetAttributeValueType()))
                            {
                                attributes[i].SetMAttributeInstance(_M_AttributeSetInstance_ID, (decimal?)lst[attributes[i]]);
                            }
                            else
                            {
                                attributes[i].SetMAttributeInstance(_M_AttributeSetInstance_ID, (String)lst[attributes[i]]);
                            }

                        }
                        _masi.SetDescription();
                        _masi.Save();

                        Dispatcher.BeginInvoke(delegate
                        {
                            _M_AttributeSetInstance_ID = _masi.GetM_AttributeSetInstance_ID();
                            _M_AttributeSetInstanceName = _masi.GetDescription();
                            //
                            if (mandatory.Length > 0)
                            {
                                Classes.ShowMessage.Error("FillMandatory", null, mandatory);
                                SetBusy(false);
                                return;
                            }
                            this.DialogResult = true;
                        });
                    });
                }

                else
                {

                    _M_AttributeSetInstance_ID = _masi.GetM_AttributeSetInstance_ID();
                    _M_AttributeSetInstanceName = _masi.GetDescription();
                    //
                    if (mandatory.Length > 0)
                    {
                        Classes.ShowMessage.Error("FillMandatory", null, mandatory);
                        SetBusy(false);
                        return;
                    }

                    this.DialogResult = true;
                }
            };
            bgw.RunWorkerAsync();
        }

        private void CancelButton_Click(object sender, RoutedEventArgs e)
        {
            _changed = false;
            _M_AttributeSetInstance_ID = 0;
            _M_Locator_ID = 0;
            this.DialogResult = false;
        }

        protected override void OnClosing(CancelEventArgs e)
        {
            Dispose();
            base.OnClosing(e);
        }


        /// <summary>
        /// Value Changed
        /// </summary>
        /// <returns></returns>
        public bool IsChanged()
        {
            return _changed;
        }

        /// <summary>
        ///Get Instance Name
        /// </summary>
        /// <returns></returns>
        public String GetM_AttributeSetInstanceName()
        {
            return _M_AttributeSetInstanceName;
        }

        /// <summary>
        ///    Get Instance ID
        /// </summary>
        /// <returns></returns>
        public int GetM_AttributeSetInstance_ID()
        {
            return _M_AttributeSetInstance_ID;
        }

        private void Dispose()
        {
            attributesList.Clear();
            attributesList = null;
            chkNewEdit = null;
            btnSelect = null;
            txtLotString = null;
            cmbLot = null;
            txtSerNo = null;
            dtpicGuaranteeDate = null;
            txtDescription = null;

            Envs.ClearWinContext(_windowNo);
            //
            Envs.GetContext().SetContext(Envs.WINDOW_INFO, Envs.TAB_INFO, "M_AttributeSetInstance_ID",
                _M_AttributeSetInstance_ID.ToString());
            Envs.GetContext().SetContext(Envs.WINDOW_INFO, Envs.TAB_INFO, "M_Locator_ID",
                _M_Locator_ID.ToString());
        }

        private void busyWindow_MouseLeftButtonDown(object sender, MouseButtonEventArgs e)
        {
            e.Handled = true;
        }


        private bool CheckAttrib(String lotString)
        {
            string sql = "";
            bool check = false;
            IDataReader idr = null;
            try
            {
                sql = "SELECT COUNT(*) FROM M_Storage s INNER JOIN M_Locator l ON (l.M_Locator_ID = s.M_Locator_ID) "
                       + " inner join M_warehouse w ON (w.M_warehouse_ID = l.M_Warehouse_ID) WHERE AD_Client_ID = " + Envs.GetCtx().GetAD_Client_ID();
                //sql = "select count(*) from m_attributesetinstance asi left OUTER JOIN m_storage s on (asi.m_attributesetinstance_id = asi.m_attributesetinstance_id)"
                //     + " inner join m_locator l on (l.m_locator_id = s.m_locator_id) inner join m_warehouse w on (w.M_warehouse_ID = l.M_Warehouse_ID) where AD_Client_ID = " + Env.GetCtx().GetAD_Client_ID();
                StringBuilder sqlWhere = new StringBuilder();
                int AD_Org_ID = Util.GetValueOfInt(Envs.GetCtx().GetContext(_windowNoParent, "AD_Org_ID"));

                String sqlChk = "SELECT IsOrganization, IsProduct, IsWarehouse FROM M_AttributeSet aSet INNER JOIN M_Product mp on mp.M_AttributeSet_ID = aset.M_AttributeSet_ID"
                    + " WHERE mp.M_Product_ID = " + _M_Product_ID;

                idr = VAdvantage.DataBase.DB.ExecuteReader(sqlChk);
                if (idr.Read())
                {
                    if (Util.GetValueOfString(idr[0]).ToUpper() == "Y")
                    {
                        sqlWhere.Append(" OR s.AD_Org_ID = " + AD_Org_ID);
                    }
                    if (Util.GetValueOfString(idr[1]).ToUpper() == "Y")
                    {
                        sqlWhere.Append(" OR s.M_Product_ID = " + _M_Product_ID);
                    }
                    if (Util.GetValueOfString(idr[2]).ToUpper() == "Y")
                    {
                        int M_Warehouse_ID = 0;
                        string sqlMovement = "SELECT TableName FROM AD_Table WHERE AD_Table_ID = " + Envs.GetCtx().GetContext(_windowNoParent, "BaseTable_ID");
                        if (VAdvantage.DataBase.DB.ExecuteScalar(sqlMovement).ToString().ToUpper() == "M_MOVEMENT")
                        {
                            string sqlWarehouse = "SELECT wh.M_Warehouse_ID FROM M_Warehouse wh INNER JOIN M_Locator l ON (wh.M_Warehouse_ID = l.M_Warehouse_ID) "
                        + " WHERE l.M_Locator_ID = " + Envs.GetCtx().GetContext(_windowNoParent, "M_LocatorTo_ID");
                            M_Warehouse_ID = Util.GetValueOfInt(DataBase.DB.ExecuteScalar(sqlWarehouse));
                        }
                        else
                        {
                            M_Warehouse_ID = Util.GetValueOfInt(Envs.GetCtx().GetContext(_windowNoParent, "M_Warehouse_ID"));
                        }
                        sqlWhere.Append(" OR w.M_Warehouse_ID = " + M_Warehouse_ID);
                    }
                    if (sqlWhere.Length > 0)
                    {
                        sqlWhere = sqlWhere.Remove(0, 3);
                        sql = sql + " AND (" + sqlWhere.ToString();
                        sql = sql + ") AND s.M_AttributeSetInstance_ID IN (SELECT M_AttributeSetInstance_ID FROM M_AttributeSetInstance WHERE Lot = '" + lotString + "')";
                    }
                }
                if (idr != null)
                {
                    idr.Close();
                    idr = null;
                }
                int checkProd = Util.GetValueOfInt(VAdvantage.DataBase.DB.ExecuteScalar(sql));
                if (checkProd > 0)
                {
                    check = true;
                }
            }
            catch (Exception ex)
            {
                if (idr != null)
                {
                    idr.Close();
                    idr = null;
                }
                log.SaveError(sql, ex);
            }
            return check;
        }
    }
}

